package com.easylinkin.linkappapi.gaodemap.util;

import com.alibaba.fastjson.JSONObject;
import com.easylinkin.linkappapi.gaodemap.entity.ConvertLocationResult;
import com.easylinkin.linkappapi.openapi.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpGet;

import java.util.*;
import java.util.concurrent.Callable;

/**
 * class info :转换坐标任务
 *
 * @author liuqihang
 * @date 2021/7/9 16:37
 */
@Slf4j
public class ConvertLocationTask implements Callable<Map<String, String>> {

    private String reqLocation;

    private String key;

    private String locationConvertUrl;

    private String coordsys;

    public ConvertLocationTask(String reqLocation, String coordsys, String key, String locationConvertUrl) {
        this.reqLocation = reqLocation;
        this.coordsys = coordsys;
        this.key = key;
        this.locationConvertUrl = locationConvertUrl;
    }

    @Override
    public Map<String, String> call() throws Exception {
        String[] split = reqLocation.split("\\|");
        Map<String, String> stringStringMap = sendHttpReq(Arrays.asList(split));
        return stringStringMap;
    }

    private Map<String, String> sendHttpReq(List<String> locationList){
        String url = locationConvertUrl + HttpClientUtil.asUrlParams(appendParams());
        HttpGet httpGet = new HttpGet(url);
        String result = HttpClientUtil.doGet(httpGet);
        log.info("坐标转换  高德api请求   url=" + url);
        log.info("坐标转换  高德api响应   result=" + result);
        ConvertLocationResult convertLocationResult = JSONObject.parseObject(result, ConvertLocationResult.class);
        if(convertLocationResult.getStatus().equals(0)){
            return null;
        }
        String[] locationArrays = convertLocationResult.getLocations().split(";");
        List<String> convertLocationList = Arrays.asList(locationArrays);
        return convertResultToMap(convertLocationList, locationList);
    }

    private Map<String, String> convertResultToMap(List<String> convertLocationList, List<String> locationList){
        if(locationList.size() !=convertLocationList.size()){
            return null;
        }
        Map<String, String> positionLocationMap =  new LinkedHashMap<>();
        for (int i = 0, size = locationList.size(); i < size; i++) {
            positionLocationMap.put(locationList.get(i), convertLocationList.get(i));
        }
        return  positionLocationMap;
    }

    private Map<String, Object> appendParams(){
        Map<String, Object> parametersMap = new HashMap<>(20);
        parametersMap.put("locations", reqLocation);
        parametersMap.put("coordsys", coordsys);
        parametersMap.put("key", key);
        parametersMap.put("output", "JSON");
        return parametersMap;
    }
}
